<template>
  <div>
    <el-dialog
      :visible.sync="settingUserVisibleState"
      @close="defKeys = []"
      @open="setRights(row)"
    >
      <el-tree
        :data="rightTreeList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        ref="rights"
      ></el-tree>
      <template slot="footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="setRightsSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'SettingUserDialog',
  props: ['row'],
  data() {
    return {
      //  树形的权限数据
      rightTreeList: [],
      //  树形控件的绑定对象
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      roleID: 0
    }
  },
  methods: {
    async setRights(row) {
      // 保存当前角色的id
      this.roleId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('请求数据失败！')

      this.$message.success('请求数据成功！')
      this.rightTreeList = res.data
      this.getLeafKeys(row, this.defKeys)
    },
    // 递归的形式，获取角色下所有的三级权限id，保存到defkeys中
    getLeafKeys(row, arr) {
      // 如果row没有children属性,直接push当前属性的id到数组
      if (!row.children) {
        return arr.push(row.id)
      } // 如果row有children属性,循环调用本方法,直到找到第三级
      row.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    // 权限分配提交方法
    async setRightsSubmit() {
      // 调用树形选择器的原型方法,获得已选择的key和半选择的key
      const keys = [
        ...this.$refs.rights.getCheckedKeys(),
        ...this.$refs.rights.getHalfCheckedKeys()
      ]
      const idtKeys = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idtKeys
        }
      )
      if (res.meta.status !== 200) return this.$message.error('权限分配失败！')

      this.$message.success('权限分配成功！')
      this.$emit('updateList')
      this.$store.commit('roles/settingUserVisibleState', false)
    }
  },
  computed: {
    settingUserVisibleState: {
      get() {
        return this.$store.state.roles.settingUserVisible
      },
      set() {
        this.$store.commit('roles/settingUserVisibleState', false)
      }
    }
  }
}
</script>

<style></style>
